﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Windows.Forms;

namespace CsScaning
{
    public class SoketScaning
    {
        public static string Devicename = "";
        public SoketScaning(string Devicename_)
        {
            Devicename = Devicename_;
        }
        #region 扫描
        //使用IPv4地址，流式socket方式，tcp协议传递数据
        Socket soketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public string recstr;
        int count = 0;
        int reclen;
        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="str">命令字符串</param>
        /// <returns></returns>
        public string Gocmd(string str)//命令执行
        {
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(str + Environment.NewLine);
                recstr = "";
                if (soketsend.Connected)
                    soketsend.Send(buffer);
                else
                {
                    CsLogFun.WriteToLog("扫码枪网络连接断开");
                    MessageBox.Show("提示：扫码枪网络连接断开");
                    return null;
                }
                TimeSpan timeSpanstart = new TimeSpan(DateTime.Now.Ticks);
                while (recstr.Contains("ERROR") || String.IsNullOrEmpty(recstr))
                {
                    TimeSpan timeSpanstop = new TimeSpan(DateTime.Now.Ticks);
                    TimeSpan ts = timeSpanstart.Subtract(timeSpanstop).Duration();
                    if (ts.Milliseconds > 3000)
                    {
                        recstr = "超时";
                        break;
                    }
                }
            }
            catch (Exception err)
            {
                CsLogFun.WriteToLog(err);
                MessageBox.Show("提示：扫码枪网络连接断开");
                throw new Exception("提示：" + err.Message);
            }

            return recstr;
        }
        public void Gostop(string str)//命令执行
        {
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(str + Environment.NewLine);
                //recstr = "";
                if (soketsend.Connected)
                    soketsend.Send(buffer);
                else
                {
                    CsLogFun.WriteToLog("扫码枪网络连接断开");
                    MessageBox.Show("提示：扫码枪网络连接断开");
                    return;
                }
            }
            catch (Exception err)
            {
                CsLogFun.WriteToLog(err);
                MessageBox.Show("提示：扫码枪网络连接断开");
                throw new Exception("提示：" + err.Message);
            }

        }
        #region //转化数据
        /// <summary>
        /// 十六进制字符串转化为字节数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }
        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string GetHexFromChs(string s)
        {
            //if ((s.Length % 2) != 0)
            //{
            //    s += " ";//空格
            //}
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
            }
            str = "02 " + str + " 03";
            return str;
        }
        //汉字转Unicode编码
        protected string GetUnicode(string source)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(source);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i += 2)
            {
                stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
            }
            return stringBuilder.ToString();
        }
        //Unicode转汉字
        protected string Unicode2String(string source)
        {
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                         source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
        }
        #endregion     
        public bool SoketConnetion(string ServerIP, string ServerPoint) //建立soket连接
        {
            bool Isconnetion = false;
            //连接到的目标IP
            IPAddress ip_ = IPAddress.Parse(ServerIP);
            //连接到目标IP的哪个应用(端口号！)
            IPEndPoint point_ = new IPEndPoint(ip_, int.Parse(ServerPoint));
            try
            {
                //连接到服务器,已经连接无需再连
                if (!soketsend.Connected)
                {
                    soketsend.Connect(point_);
                    Thread th = new Thread(ReceiveMsg);
                    th.IsBackground = true;
                    th.Start();
                }
                if (soketsend.Connected)
                {
                    Isconnetion = true;
                }
            }
            catch (Exception err)
            {
                CsLogFun.WriteToLog(err);
                MessageBox.Show("提示：扫码枪网络连接断开");
                throw new Exception("提示：" + err.Message);
            }
            return Isconnetion;
        }
        void ReceiveMsg()//接受服务器端返回数据信息
        {
            string strre = "";
            while (true)
            {
                try
                {
                    Thread.Sleep(1);
                    reclen = 0;
                    byte[] buffer = new byte[1024];
                    if (soketsend.Connected)
                        reclen = soketsend.Receive(buffer, buffer.Length, 0);
                    else
                    {
                        CsLogFun.WriteToLog("扫码枪网络连接断开");
                        MessageBox.Show("提示：扫码枪网络连接断开");
                        continue;
                    }
                    strre = Encoding.UTF8.GetString(buffer, 0, reclen);
                    if (reclen > 0 && !string.IsNullOrEmpty(strre))
                    {
                        recstr = strre;
                    }
                    strre = "";
                }
                catch (Exception err)
                {
                    CsLogFun.WriteToLog(err);
                    MessageBox.Show("提示：扫码枪网络连接断开");
                    throw new Exception("提示：" + err.Message);
                }
            }
        }
        #endregion
    }
}
